package com.linked.mystyle.food.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.mystyle.food.bean.FoodInfoPO;
import com.linked.mystyle.food.bean.FoodRandomParam;
import com.linked.mystyle.food.serive.IFoodService;
import com.linked.universal.common.LinkedPrompt;
import com.linked.universal.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@Slf4j
@RequestMapping("/food")
public class FoodController {

    private final IFoodService foodService;

    private final ObjectMapper mapper;

    public FoodController(IFoodService foodService, ObjectMapper mapper) {
        this.foodService = foodService;
        this.mapper = mapper;
    }

    @PostMapping("/addFood")
    Result addFood(@RequestBody FoodInfoPO param) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("添加食物接口 ----- 入参：{}", mapper.writeValueAsString(param));
        }

        boolean ret = false;
        try {
            ret = foodService.addFood(param);
        } catch (Exception e) {
            log.error("添加食物接口 ----- 异常", e);
            return Result.error(LinkedPrompt.ERROR_MESSAGE);
        }

        return ret ? Result.success(param.getFoodId()) : Result.ok(false, LinkedPrompt.ADD_FAILURE);
    }

    @PostMapping("/giveRandomFood")
    Result giveRandomFood(@RequestBody FoodRandomParam param) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("获取随机食物接口 ----- 入参：{}", mapper.writeValueAsString(param));
        }
        FoodInfoPO food = null;
        try {
            int foodCount = foodService.queryFoodTotalCount(param);
            Random random = new Random();
            int foodNum = random.nextInt(foodCount);
            food = foodService.giveRandomFood(param,foodNum);
        } catch (Exception e) {
            log.error("获取随机食物接口 ----- 异常", e);
            return Result.error(LinkedPrompt.ERROR_MESSAGE);
        }
        return Result.success(food);
    }


}
